package com.xinsmartsky.penmaji.NewGridView;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.xinsmartsky.penmaji.penmaji.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by wangxiao on 15-12-25.
 */
public class NewGridView extends ImageView {
    private Resources myResources;
    // 画布及其底层位图
    private Canvas myCanvas;
    private Bitmap myBitmap;
    private Paint paint, paintdel, gPaint, myBitmapPaint;
    //横向方格个数---初始化
    private int HOR_NUM = 8;
    //纵向方格数
    private int PORT_NUM = 8;
    //网格 边长
    private float length = (float) 10.0;
    private Set<RectF> rectsf = new HashSet<RectF>();//不重复的矩形集合
    private boolean flag = true;
    //iterator----迭代器
    //next--第一次调用返回第一个元素
    //hasNext----检查是否还有元素
    private float startx, starty;
    private int col, row, subscript, i;
    private byte[] value;

    public NewGridView(Context context) {
        super(context);
        initialize();
    }

    public NewGridView(Context context, AttributeSet attr) {
        super(context, attr);
        initialize();
    }

    public NewGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize();
    }
    /*
    * 初始化
    * */
    private void initialize()
    {
        myResources = getResources();
        //矩形 画笔
        paint = new Paint();
        paint.setColor(myResources.getColor(R.color.white));
        paint.setAntiAlias(true);//设置画笔抗锯齿
        paint.setDither(true);//防抖动
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);//画笔圆滑状
        paint.setStrokeWidth(1);
        //网格 画笔
        gPaint = new Paint();
        gPaint.setColor(Color.GRAY);
        paint.setDither(true);//防抖动
        gPaint.setAntiAlias(true);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);//画笔圆滑状
        gPaint.setStyle(Paint.Style.STROKE);
        gPaint.setStrokeWidth(1);
        //删除矩形的画笔
        paintdel = new Paint();
        paintdel.setColor(myResources.getColor(R.color.black));
        paintdel.setAntiAlias(true);//设置画笔抗锯齿
        paintdel.setDither(true);//防抖动
        paintdel.setStyle(Paint.Style.FILL);
        paintdel.setStrokeJoin(Paint.Join.ROUND);
        paintdel.setStrokeCap(Paint.Cap.ROUND);//画笔圆滑状
        paintdel.setStrokeWidth(1);
        myBitmapPaint = new Paint(Paint.DITHER_FLAG);//无锯齿
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i("vvv", "w = " + w + "    h = " + h + "     oldw" + oldw + "   oldh" + oldh);
        Log.i("zzz", "onSizeChanged=================================");
        if (w > 0 && h > 0) {
            Log.i("vvv", "w > 0===============");
            myBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            myCanvas = new Canvas(myBitmap);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.BLACK);//设置画布颜色
        canvas.drawBitmap(myBitmap, 0, 0, myBitmapPaint);
        Log.i("zzz", "onDraw=================================");
        if(flag)
        {
            gridrect();//画网格
            flag = false;
        }
    }

    /*由数组画出图形 8的倍数*/
    public void ChineseDrid_8n(byte[] CArray, int dianzhen) {
        if(tag){
            Log.i("qqq", "settag1");
            this.setTag("1");//标记有图画的布局--删除按钮
            tag = false;
        }
        byte[] Arraytemp = new byte[CArray.length];
        byte num = 0;
        int temp = 0;
        int dianzhenmul = dianzhen / 8;//取值 2 3 4
                //使显示的汉字为正
//                for (int index = 0; index < CArray.length; index++) {
//                    if (index % 2 == 1) {
//                        temp = (index - 1);
//                    } else {
//                        temp = (index + 1);
//                    }
//                    Arraytemp[temp] = CArray[index];
//                    //0-7位换位置
//                    for (int i = 0; i < 8; i++) {
//                        num |= (((Arraytemp[temp] >> i) & 0x1) << (7 - i));
//                    }
//                    Arraytemp[temp] = num;
//                    num = 0;
//                }
        Log.i("fff", "数组长度============" + CArray.length + "    点阵" + dianzhen);
        for (int i = 0; i < CArray.length; i++) {
            for (int j = 0; j < 8; j++) {
                if (((Arraytemp[i] >> (7 - j)) & 0x1) == 1) {//由最高位开始
                    Log.i("fff", "数组下标============" + i +"zzz" +  dianzhenmul);
                    //列 : i/2  行： i % 2 * 8 + (7 - j)
                     myCanvas.drawRect(length * (i / dianzhenmul), length * (i % dianzhenmul * 8 + j), length * (i / dianzhenmul + 1), length * (i % dianzhenmul * 8 + j + 1), paint);
                }
            }
        }
    }


    private boolean iferaser = false;

    //删除矩形
    public void eraser() {
        if(iferaser)
        {
            iferaser = false;
        }else{
            iferaser = true;
        }
    }

    private RectF rectftemp = new RectF();
    private RectF rectfnext = new RectF();
    private Iterator<RectF> iter;
    private boolean isequal = false;
    private boolean tag = true;
    private void action_down(float x, float y)
    {
        startx = ((int) (x / length)) * length;
        starty = ((int) (y / length)) * length;
        //将矩形放入集合中
        if(iferaser) //如果打开了橡皮擦功能 - 可以删除矩形
        {
            iter = rectsf.iterator();
            while(iter.hasNext())
            {
                rectfnext = iter.next();
                if(rectftemp.equals(rectfnext))
                {
                    isequal = true;
                    //如果点击的矩形的等于集合中的值  将这个值删除
                    iter.remove();
                    myCanvas.drawRect(rectftemp, paintdel);
                }
            }
        }
        //如果无相同的矩形 画在屏幕上
        if(!isequal){
            myCanvas.drawRect(startx, starty, startx + length, starty + length, paint);
            rectftemp.set(startx, starty, startx + length, starty + length);
            rectsf.add(rectftemp);//加入集合
            Log.i("xxx", "长度1" + rectftemp.centerX() + "," + rectftemp.centerY());
        }
    }

    private void action_move(float x, float y)
    {
        startx = ((int) (x / length)) * length;
        starty = ((int) (y / length)) * length;
        if (!iferaser) {//调用橡皮擦后 使MOVE不起作用
            myCanvas.drawRect(startx, starty, startx + length, starty + length, paint);
            rectftemp.set(startx, starty, startx + length, starty + length);
            rectsf.add(rectftemp);//加入集合
            Log.i("xxx", "长度1" + rectftemp.centerX() + "," + rectftemp.centerY());
        }
    }

    @Override
    public synchronized boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                action_down(x, y);
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                action_move(x, y);
                break;
            }
        }
        invalidate();//刷新屏幕?????????????????
        return true;//使点击事件不继续传递(如果有键盘点击事件)
    }


    //设置横向网格个数
    public void setHOR_num(int num) {
        this.HOR_NUM = num;
    }


    //设置纵向网格个数
    public void setPort_num(int num) {

        this.PORT_NUM = num;
    }

    //设置网格边长
    public void setLength(float length) {

        this.length = length;
    }

    /*清除图像*/
//    public void clear()
//    {
//        rectsf.clear();//清除矩形
//        myBitmap.eraseColor(myResources.getColor(R.color.black));
//        gridrect();
//        invalidate();
//    }

    //将迭代器中的元素加入到数组中
    public byte[] getDrawArray(int matrix) {
        Iterator<RectF> iter = rectsf.iterator();
        //输出集合
        value = new byte[matrix * 120 / 8];
        if (matrix % 8 == 0) {
            while (iter.hasNext()) {
                RectF point = iter.next();//遍历迭代器中的矩形
                Log.i("xxx","------------------------------------" + "长度" + rectsf.size() + "   坐标"+ (point.centerX() + point.centerY()));
                col = (int) ((point.centerX()) / length +1);//列号 1~
                row = (int) ((point.centerY()) / length +1);//行号 1~

                subscript = (matrix / 8) * (col - 1) + (matrix / 8 - 1)-(row - 1) / 8;//下标
                i = row-1-8*((row-1)/8);//移位
                value[subscript] |= (0x1 << i);//加入到数组中
                Log.i("xxx", "列好 = " + col + "   行号 = " + row + "   下标1=" + subscript + "  值 = " + value[subscript]);
            }
        }
//        for(int i = 0; i < value.length; i++){
//            Log.i("xxx", "下标2 = " + i + "  值 = " + value[i]);
//        }
        return value;
    }

    //画背景网格
    public void gridrect() {
        for (int i = 0; i < PORT_NUM; i++) {
            for (int j = 0; j < HOR_NUM; j++) {
                myCanvas.drawRect(j * length, (i * length), length * (j + 1), (length * (i + 1)), gPaint);
            }
        }
    }

    private int dianzhennum = 0;
    /*传入字符串 在屏幕上显示汉字图形
    * Chinese：字符串
    * MatLastNum：点阵
    * edit_lin_gridview：父布局*/
    public byte[] ChineseShow(String Chinese, int MatLastNum, LinearLayout lin_gridview) {
        byte[] ArrayLong;
        dianzhennum = MatLastNum;
        ArrayLong = ChineseToGraph(Chinese, lin_gridview);
        return ArrayLong;
    }

    /*传入数组 在屏幕上显示图形*/
    public void DrawingShow(byte[] drawing, int MatLastNum,LinearLayout lin_gridview){
        NewGridView gridViewmax = (NewGridView) (lin_gridview.getChildAt(0)).findViewById(R.id.draw_ngv_newview);
        gridViewmax.ChineseDrid_8n(drawing, MatLastNum);
    }

    //获取最后一个有图案的下标
    public int getlastnum(LinearLayout lin_gridview){
        last_num = -1;
        for (int k = 0; k < lin_gridview.getChildCount(); k++){
            gridView = (NewGridView) (lin_gridview.getChildAt(k)).findViewById(R.id.edit_ngv_newview);
            if (gridView.getTag() != null) {
                last_num = k;
            }
        }
        return last_num;
    }
    private int last_num = -1;
    //画图形
    NewGridView gridView;
    byte[] ArrayLong;
    public byte[] ChineseToGraph(String Chinese, LinearLayout lin_gridview) {
        String hzk = "/storage/sd_external/HZK/HZK" + dianzhennum;
        ReadHZK readhzk = new ReadHZK();
        int bytenum = 32;//字节个数(ArrayC的长度)
        int i;
        ArrayLong = new byte[bytenum * (Chinese.length())];//用于记录多个文字的数组
        int lastnum;
        for (i = 0; i < Chinese.length(); i++) {
            byte[] ArrayC = new byte[bytenum];//记录一个汉字的数组
            try {
                for (int j = 0; j < ArrayC.length; j++) {
                    ArrayC[j] = (readhzk.ReadHZKnumread(hzk, Chinese.substring(i, i + 1), dianzhennum))[j];
                }
                //从没有图案的后一个开始写字
                gridView = (NewGridView) (lin_gridview.getChildAt(getlastnum(lin_gridview) + 1)).findViewById(R.id.edit_ngv_newview);
                gridView.ChineseDrid_8n(ArrayC, dianzhennum);
            } catch (IOException e) {
                e.printStackTrace();
            }

            for (int numm = 0; numm < ArrayC.length; numm++) {
                ArrayLong[bytenum * i + numm] = ArrayC[numm];//每个字的数组追加到长数组里
            }
        }
        return ArrayLong;
    }


}
